﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace ProductCollector {
    public class WalmartSearcher :ISiteSearcher
    {
        private const string SEARCH_URL =
            "http://www.walmart.com/search/search-ng.do?tab_value=all&search_query={0}&search_constraint=0&Find=Find&ss=false&ic=16_{1}";

        private const string HOME_URL = "http://www.walmart.com";
        public IList<Product> Search(SearchCriteria criteria) {
            var web = new HtmlWeb();
            criteria.NumOfProduct = 16;// NoOfProduct for this site is 16 or 32 :(
            string url = string.Format(SEARCH_URL, criteria.SearchValue, criteria.CurrentPageIndex * criteria.NumOfProduct);
            List<Product> result = new List<Product>();

            HtmlDocument doc = web.Load(url);
            var gridNode = doc.DocumentNode.SelectSingleNode("//div[@id='border']");
            if (gridNode == null) {
                return result;
            }
            var allProds = gridNode.SelectNodes("./div[contains(@class,'item')]");

            foreach (HtmlNode node in allProds) {
                Product p = GetProductByNode(node);
                if (p != null) {
                    result.Add(p);
                }
                if (result.Count >= criteria.NumOfProduct) {
                    break;
                }
            }
            return result;
        }
        private Product GetProductByNode(HtmlNode liNode) {
            Product p = new Product();
            var atopLink = liNode.SelectSingleNode("./div[contains(@class,'compare')]/a");
            if (atopLink != null) {
                p.OriginalUrl = atopLink.GetAttributeValue("href", HOME_URL);
                var img = atopLink.SelectSingleNode("./img");
                if (img != null) {
                    p.ThumbImg = img.GetAttributeValue("src", HOME_URL);
                }
            }
            var title = liNode.SelectSingleNode("./div/div[contains(@class,'prodInfoBox')]/a[contains(@class,'prodLink')]");
            if (title != null) {
                p.ProductName = title.InnerText;
            }
            var prodDesc = liNode.SelectSingleNode("./div/div[contains(@class,'prodInfoBox')]/table[contains(@class,'ProdDescContainer')]/tbody/tr/td/div[contains(@class,'ProdDesc')]");
            if(prodDesc != null)
            {
                p.Description = prodDesc.InnerText;
            }
            var price = liNode.SelectSingleNode("./div[contains(@class,'ItemShelfAvail')]/div/div[contains(@class,'PriceContent')]/div/div/div[contains(@class,'camelPrice')]");

            if (price != null) {
                p.FormattedPrice = price.InnerText;
            }

            return p;
        }
        public int CountProduct(SearchCriteria criteria) {
            throw new NotImplementedException();
        }
    }
}
